package com.dily.study.subTable.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Date: 2022-08-15 星期一
 * Time: 10:17
 * Author: Dily_Su
 * Remark:
 */
@Configuration
@MapperScan(basePackages = "com.dily.study.subTable.mapper")
public class MybatisConfig {

    @Value("#{'${subTable.tableNames}'.split('.')}")
    private List<String> tableNames;

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
        dynamicTableNameParser.setTableNameHandlerMap(
                new HashMap<>(2) {
                    {
                        //涉及表集合
                        List<String> tables = tableNames;
                        //动态表规则 初始表名+_+code
                        tables.forEach(tableTitle -> put(tableTitle, (metaObject, sql, tableName) -> tableName + getParamValue("month", metaObject)));
                    }
                });
        paginationInterceptor.setSqlParserList(Collections.singletonList(dynamicTableNameParser));
        return paginationInterceptor;
    }

    /**
     * @param title      分表字段
     * @param metaObject 对象
     * @return 表名尾缀
     */
    private Object getParamValue(String title, MetaObject metaObject) {
        //获取参数
        Object originalObject = metaObject.getOriginalObject();
        JSONObject originalObjectJSON = JSON.parseObject(JSON.toJSONString(originalObject));
        JSONObject boundSql = originalObjectJSON.getJSONObject("boundSql");
        JSONObject parameterObject = boundSql.getJSONObject("parameterObject");
        // 按月分表
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM");
        // 按天分表
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        if (parameterObject.get(title) == null) {
            return "";
        }
        Date date = parameterObject.getObject(title, Date.class);
        return "_" + formatter.format(date);
    }
}
